package com.xc.service.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.xc.service.client.UserClient;
import com.xc.service.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

@Controller
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "fallBackMethod") // 指定一个类的全局熔断方法
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient; // eureka客户端，可以获取到eureka中服务的信息

    @Autowired
    private UserClient userClient;

    @GetMapping("/user/{id}")
    @ResponseBody
    @HystrixCommand//表示改方法需要熔断，熔断为全局默认熔断
    //@HystrixCommand(fallbackMethod = "queryUserByIdFallBack")//局部熔断方法
    public String queryUserById(@PathVariable("id") Long id) {
        // 根据服务名称，获取服务实例。有可能是集群，所以是service实例集合
        //List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
        // 因为只有一个Service-provider。所以获取第一个实例
        //ServiceInstance instance = instances.get(0);
        // 获取ip和端口信息，拼接成服务地址
        //String baseUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/user/" + id;
        //直接通过服务名来获取
//        if(id == 1){//测试熔断次数
//            throw new RuntimeException("太忙了");
//        }
//        String baseUrl = "http://service-provider/user/" + id;
//        String user = this.restTemplate.getForObject(baseUrl, String.class);
        User user = this.restTemplate.getForObject("http://localhost:8081/user/" + id, User.class);
        //restTemplate.getForEntity("",User.class);
        //User user = userClient.queryById(id);
        return user.toString();
    }

    public String queryUserByIdFallBack(Long id) {//相同的参数列表和返回值声明
        return "请求繁忙，请稍后再试！";
    }

    /**
     * 熔断方法
     * 返回值要和被熔断的方法的返回值一致
     * 熔断方法不需要参数
     *
     * @return
     */
    public String fallBackMethod() {
        return "请求繁忙，请稍后再试！";
    }

}
